package com.google.api.client.sample.project;

import com.google.api.client.extensions.appengine.http.urlfetch.UrlFetchTransport;
import com.google.api.client.extensions.auth.helpers.TwoLeggedFlow;
import com.google.api.client.extensions.servlet.auth.AbstractTwoLeggedFlowServlet;
import com.google.api.client.googleapis.extensions.auth.helpers.appengine.GoogleAppAssertionFlow;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;

public class ArticleApp extends AbstractTwoLeggedFlowServlet {

  private static final Logger log = Logger.getLogger(ArticleApp.class.getName());

  public ArticleApp() {
  }

  protected void service(HttpServletRequest req, HttpServletResponse servletResponse)
      throws IOException {
    javax.jdo.PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
    req.setAttribute("com.google.api.client.extensions.servlet.auth.persistence_manager", pm);
    log.info((new StringBuilder()).append("acct name == ").append(getUserId()).toString());
    com.google.api.client.extensions.auth.helpers.Credential auth = getCredential(req);
    GoogleStorage storage =
        new GoogleStorage(super.getHttpTransport(), auth, super.getJsonFactory());
    HttpResponse res = storage.listBuckets();
    servletResponse.setContentType("text/xml");
    java.io.PrintWriter out = servletResponse.getWriter();
    InputStreamReader inputStreamReader = new InputStreamReader(res.getContent());
    IOUtils.copy(inputStreamReader, out);
  }

  protected TwoLeggedFlow newFlow(String userId) {
    return new GoogleAppAssertionFlow(userId,
        "https://www.googleapis.com/auth/devstorage.full_control", getHttpTransport(),
        getJsonFactory());
  }

  protected String getUserId() {
    AppIdentityService service = AppIdentityServiceFactory.getAppIdentityService();
    return service.getServiceAccountName();
  }

  protected PersistenceManagerFactory getPersistenceManagerFactory() {
    return PMF.get();
  }

  protected HttpTransport newHttpTransportInstance() {
    return new UrlFetchTransport();
  }

  protected JsonFactory newJsonFactoryInstance() {
    return new GsonFactory();
  }

}
